import calculateWinner from './calculateWinner.js'
const createMove = (id) => ({
    type: 'MOVE',
    id
})
const backMove = (id) => ({
    type: 'BACK',
    id
})
const back = (state = 0, action) => {
    if(action.type == 'BACK')
        return acion.id
    return state
}
const InitialState = {
    history: [{squares: Array(9).fill(null)}],
    stepNumber: 0,
    xIsNext: true
}

const move = (state = InitialState, action) => {
    switch (action.type){
        case 'MOVE':
            const history = state.history.slice(0, state.stepNumber + 1);
            const current = history[history.length - 1];
            const squares = current.squares.slice();
             // state constraint: game is not over and current square does not have stone
            if(calculateWinner(squares) || squares[action.id])
                return state  
            squares[action.id] = state.xIsNext ? "X" : "O";  
            return {
                history: history.concat([
                  {
                    squares: squares
                  }
                ]),
                stepNumber: history.length,
                xIsNext: !state.xIsNext
              }    
        case 'BACK':
            // state constraint: stepNumber + 1 <= history.length
            if(action.id + 1 > state.history.length)
                return state
            return Object.assign({}, state, {
                stepNumber: action.id,
                xIsNext: (action.id % 2) === 0
              })      
        default:
            return state
    }
}
export {InitialState, createMove, backMove, move};